package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Customer;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.query.CustomerQueryObject;
import cn.wolfcode.crm.service.ICustomerService;
import cn.wolfcode.crm.service.ISystemDictionaryItemService;
import cn.wolfcode.crm.util.JSONResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/customer")
public class CustomerController {
	
	@Autowired
	private ICustomerService customerService;

	@Autowired
	private ISystemDictionaryItemService dictionaryItemService;

	@RequestMapping("list")
	public String list(Model model, @ModelAttribute("qo")CustomerQueryObject qo){
		Subject subject = SecurityUtils.getSubject();
		if(!(subject.hasRole("admin") || subject.hasRole("marker_manager"))){
			Employee employee = (Employee) subject.getPrincipal();
			qo.setSellerId(employee.getId());
		}
		model.addAttribute("traceTypes",dictionaryItemService.listItemBySn("communicationMethod"));
		model.addAttribute("result", customerService.query(qo));
		model.addAttribute("jobs",dictionaryItemService.listItemBySn("job"));
		model.addAttribute("sources",dictionaryItemService.listItemBySn("source"));
		return "/customer/list";
	}



	@RequestMapping("/saveOrUpdate")
	@ResponseBody
	public Object saveOrUpdate(Customer entity){
		JSONResult result = new JSONResult();
		try {
			//int i = 1/0;
			if(entity.getId() != null){
                customerService.updateByPrimaryKey(entity);
            }else{
                customerService.insert(entity);
            }
		} catch (Exception e) {
			e.printStackTrace();
			result.mark(e.getMessage());
		}

		return result;
	}

}
